package com.loeng.module.infra.dal.mysql.job;

import com.loeng.framework.common.pojo.PageResult;
import com.loeng.framework.mybatis.core.mapper.BaseMapperX;
import com.loeng.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.loeng.module.infra.controller.admin.job.vo.log.JobLogPageReqVO;
import com.loeng.module.infra.dal.dataobject.job.JobLogDO;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;

/**
 * 定时任务日志 Mapper
 *
 * @author loeng zhuo
 */
@Mapper
public interface JobLogMapper extends BaseMapperX<JobLogDO> {

    /**
     * 获得定时任务日志分页
     *
     * @param reqVO 分页查询
     * @return 定时任务日志分页
     */
    default PageResult<JobLogDO> selectPage(JobLogPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<JobLogDO>()
                .eqIfPresent(JobLogDO::getJobId, reqVO.getJobId())
                .likeIfPresent(JobLogDO::getHandlerName, reqVO.getHandlerName())
                .eqIfPresent(JobLogDO::getHandlerParam, reqVO.getHandlerParam())
                .eqIfPresent(JobLogDO::getExecuteIndex, reqVO.getExecuteIndex())
                .betweenIfPresent(JobLogDO::getBeginTime, reqVO.getBeginTime())
                .betweenIfPresent(JobLogDO::getEndTime, reqVO.getEndTime())
                .eqIfPresent(JobLogDO::getDuration, reqVO.getDuration())
                .eqIfPresent(JobLogDO::getStatus, reqVO.getStatus())
                .eqIfPresent(JobLogDO::getResult, reqVO.getResult())
                .betweenIfPresent(JobLogDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(JobLogDO::getId));
    }

    /**
     * 物理删除指定时间之前的日志
     *
     * @param createTime 最大时间
     * @param limit 删除条数，防止一次删除太多
     * @return 删除条数
     */
    default Integer deleteByCreateTimeLt(LocalDateTime createTime, Integer limit) {
        return delete(new LambdaQueryWrapperX<JobLogDO>()
                .lt(JobLogDO::getCreateTime, createTime)
                .last("LIMIT " + limit));
    }
}